package com.xnyzc.lhy.common.component.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description:
 * @Author: scootXin
 * @Date: 2019/4/16 14:48
 */
@Slf4j
@Configuration
public class HttpClientConfig {

    @Value("${feign.pangconfig.max}")
    private int max;
    @Value("${feign.pangconfig.defMaxPerRoute}")
    private int defMaxPerRoute;

    @Value("${feign.pangconfig.connectTimeout}")
    private int connectTimeout;
    @Value("${feign.pangconfig.socketTimeout}")
    private int socketTimeout;
    @Value("${feign.pangconfig.connectRequestTimeout}")
    private int connectRequestTimeout;

    @Bean
    public HttpClient httpClient(HttpClientBuilder httpClientBuilder) {
        return httpClientBuilder.build();
    }

    @Bean(destroyMethod = "close")
    public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager() {
        PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
        manager.setMaxTotal(max);
        manager.setDefaultMaxPerRoute(defMaxPerRoute);
        return manager;
    }

    @Bean
    public HttpClientBuilder httpClientBuilder(HttpClientConnectionManager httpClientConnectionManager) {
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout)
                .setConnectionRequestTimeout(connectRequestTimeout).build();

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setConnectionManager(httpClientConnectionManager);
        httpClientBuilder.setDefaultRequestConfig(requestConfig);
        httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

        return httpClientBuilder;
    }

}
